<template>
  <el-container>
    <el-header>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>{{ title[0] }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ title[1] }}</el-breadcrumb-item>
      </el-breadcrumb>
      <h3>{{ title[1] }}</h3>

    </el-header>
    <el-container>
      <el-aside width="200px">

        <el-input placeholder="输入关键字进行过滤"
                  v-model="filterText">
        </el-input>

        <el-tree class="filter-tree"
                 :data="data"
                 :props="defaultProps"
                 default-expand-all
                 :filter-node-method="filterNode"
                 ref="tree"
                 @node-click="find">
        </el-tree>

      </el-aside>
      <el-main>
        <el-container>

          <div>
            <el-form :inline="true"
                     :model="formInline"
                     class="list-search">

              <el-form-item label="试题题干：">
                <el-input size="mini"
                          v-model="formInline.Qtopic"
                          placeholder="请输入"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="试题类型：">
                <el-select size="mini"
                           v-model="formInline.Qtype"
                           placeholder="请选择"
                           clearable>
                  <el-option label="单选"
                             value="1"></el-option>
                  <el-option label="多选"
                             value="2"></el-option>
                  <el-option label="判断"
                             value="3"></el-option>
                  <el-option label="填空"
                             value="4"></el-option>
                  <el-option label="阅读"
                             value="5"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="mini"
                           type="primary"
                           icon="el-icon-search"
                           @click="search">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="mod-btnbox">
            <el-button size="small"
                       type="primary"
                       icon="el-icon-plus"
                       @click="addQuestion">新增试题</el-button>
            <el-button size="small"
                       type="primary"
                       icon="el-icon-circle-plus"
                       @click="dialog = true"
                       plain>批量导入</el-button>
            <el-button size="small"
                       type="primary"
                       icon="el-icon-delete-solid"
                       @click="deleteManyQ"
                       plain>批量删除
            </el-button>
          </div>
          <!-- 详情弹窗 -->
          <el-dialog title="题目详情"
                     :visible.sync="editFormVisible"
                     width="60%"
                     @click="closeDialog">
            <el-descriptions title=""
                             v-if="editForm[0].text">
              <el-descriptions-item label="阅读">{{editForm[0].text}}</el-descriptions-item>
            </el-descriptions>
            <div v-for="item in editForm"
                 :key="item.id">
              <el-descriptions title="">
                <el-descriptions-item label="题干">{{item.topic}}</el-descriptions-item>
              </el-descriptions>
              <el-table :data="item.options">
                <el-table-column label="选项"
                                 show-overflow-tooltip>
                  <template slot-scope="scope">{{scope.row.opt}}
                    <el-tag v-if="scope.row.status === 'y'"
                            type="success"
                            effect="dark">
                      正确答案
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-button type="primary"
                       @click="dialog = true">添加到试卷<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-dialog>

          <el-drawer title="试卷列表"
                     :before-close="handleClose"
                     :visible.sync="dialog"
                     direction="rtl"
                     custom-class="demo-drawer"
                     ref="drawer"
                     size="650px">
            <div class="demo-drawer__content">
              <el-form :model="form">
                <el-form-item label="选择试卷"
                              :label-width="formLabelWidth">
                  <el-cascader :options="tableData2"
                               :props="cateListProps"
                               @change="handlechange">
                    <template slot-scope="{ node }">
                      <span>{{node.label}}</span>
                      <span v-if="!node.isLeaf"> ({{ node.children.length }}) </span>
                    </template>
                  </el-cascader>
                  <el-select v-model="paperItem"
                             placeholder="请选择试卷名称"
                             value-key="name">
                    <el-option v-for="item in paperItems"
                               :key="item.id"
                               :label="item.name"
                               :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="分数">
                  <el-input v-model="form.score"
                            placeholder="请输入题目分数"></el-input>
                </el-form-item>
              </el-form>
              <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取 消</el-button>
                <!-- @click="$refs.drawer.closeDrawer()" -->
                <el-button type="primary"
                           @click="$refs.drawer.closeDrawer()"
                           :loading="loading">{{ loading ? '添加中 ...' : '添  加' }}</el-button>
              </div>
            </div>
          </el-drawer>

          <el-main>
            <template>
              <el-table ref="multipleTable"
                        :data="tableData"
                        highlight-current-row
                        v-loading="loading"
                        border
                        element-loading-text="拼命加载中"
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="handleSelectionChange"
                        height="450">
                <el-table-column type="selection"
                                 width="55">
                </el-table-column>
                <el-table-column align="center"
                                 sortable
                                 prop="id"
                                 label="题号"
                                 width="120">
                </el-table-column>
                <el-table-column prop="topic"
                                 label="试题题干"
                                 align="center">
                </el-table-column>
                <el-table-column prop="questionType.type"
                                 label="试题类型"
                                 align="center"
                                 show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-row>
                      <el-button size="mini"
                                 plain
                                 @click="handleEdit()">修改</el-button>
                      <el-button size="mini"
                                 type="danger"
                                 plain
                                 @click="deleteQ(scope.$index, scope.row)">删除
                      </el-button>
                      <el-button size="mini"
                                 type="primary"
                                 plain
                                 @click="showmore(scope.$index, scope.row)">详情
                      </el-button>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>

            </template>
          </el-main>
          <el-footer>
            <!-- 分页组件 -->
            <Pagination v-bind:child-msg="pageparm"
                        @callFather="callFather"></Pagination>
          </el-footer>
        </el-container>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
// 导入组件
// import headerComponent from "./head.vue";
//导入方法
import {
  iList,
  QuList,
  findQubyid,
  deleteQbyid,
  findQbyid,
  findPaperItemByCategoryId,
  addItemToPaper,
} from '../../api/qList'
import { pList } from '../../api/paperMG'
//分页组件
import Pagination from '../../components/Pagination'
// 导出模块
export default {
  // 模块名字
  name: 'questionList',
  // 模块数据
  data() {
    //数据
    return {
      //树形菜单过滤文本
      filterText: '',
      //树形菜单题库分类数据
      data: [],
      //树形菜单属性
      defaultProps: {
        children: 'questionInventories',
        label: 'subject',
      },
      //表格中的数据
      tableData: [],
      //试卷分类级联菜单中的数据
      tableData2: [],
      multipleSelection: [],
      //页面头部声明
      title: '',
      editFormVisible: false, //控制编辑页面显示与隐藏
      // rules 表单验证
      rules: {
        Qoption: [
          { required: true, message: '请输入试题题干', trigger: 'blur' },
        ],
        Qtype: [{ required: true, message: '请输入试题类型', trigger: 'blur' }],
        Qdifficulty: [
          { required: true, message: '请输入试题难度', trigger: 'blur' },
        ],
      },
      formInline: {
        page: 1,
        limit: 10,
        deptId: '',
        Qtopic: '',
        Qtype: '',
        //树形菜单编号数组
        ids: [],
      },
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
      //题目详情信息
      editForm: [
        {
          topic: '',
          options: [],
          typeid: '',
          text: '',
        },
      ],
      //试卷列表抽屉弹窗
      dialog: false,
      loading: false,
      //保存试卷题目以及对应分数
      form: {
        score: '',
      },
      formLabelWidth: '100px',
      timer: null,
      //试卷列表级联菜单自定义属性
      cateListProps: {
        value: 'id',
        label: 'name',
        children: 'paperCategories',
        checkStrictly: true,
      },
      //保存根据试卷分类查到的试卷数组
      paperItems: [],
      //保存选中的具体试卷
      paperItem: '',
    }
  },
  // 注册组件
  components: {
    // headerComponent
    Pagination,
  },
  // 监听指定值，只有指定值变化，才会触发
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    //给题目列表添加详情弹窗监听事件
    editFormVisible: 'changeEdit',
  },
  // 里面的函数只有调用才会执行（实时计算）里面是定义的方法
  methods: {
    //点击树形菜单显示对应题库分类下的所有题目
    find(data) {
      this.formInline.ids = []
      this.getIds(data)
      this.getdata(this.formInline)
    },
    //根据题库分类树形菜单传来的分类集合生成包含该分类以及其子分类下的id数组
    getIds(parameter) {
      this.formInline.ids.push(parameter.id)
      for (let i = 0; i < parameter.questionInventories.length; i++) {
        if (parameter.questionInventories[i].questionInventories.length > 0) {
          this.getIds(parameter.questionInventories[i])
        } else {
          this.formInline.ids.push(parameter.questionInventories[i].id)
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.subject.indexOf(value) !== -1
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    addFun() {},
    submitFun() {},
    addQuestion() {
      this.$router.push({
        path: '/system/addQuestion/danxuan',
      })
    },
    //批量删除
    deleteManyQ() {
      alert('批量删除')
    },
    getdata(parameter) {
      ;(this.loading = true),
        /***
         * 调用接口，渲染题目列表
         */
        QuList(parameter)
          .then((res) => {
            this.loading = false
            if (res.data.code != 200) {
              this.$message({
                type: 'info',
                message: res.msg,
              })
            } else {
              this.tableData = res.data.data.list
              // 分页赋值
              this.pageparm.currentPage = this.formInline.page
              this.pageparm.pageSize = this.formInline.limit
              this.pageparm.total = res.data.data.total
            }
          })
          .catch((err) => {
            this.loading = false
            this.$message.error('获取题目列表失败，请稍后再试！')
          })
    },
    //列表操作
    handleEdit() {
      alert('修改')
    },
    deleteQ(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 删除
          deleteQbyid(row.id)
            .then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '数据已删除!',
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
            .catch((err) => {
              this.loading = false
              this.$message.error('数据删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！',
          })
        })
    },
    showmore(index, row) {
      this.editFormVisible = true
      // 读取详情
      if (row.questionType.id != 5) {
        findQbyid(row.id)
          .then((res) => {
            this.editForm = res.data.data
          })
          .catch((err) => {
            this.loading = false
            this.$message.error('读取失败，请稍后再试！')
          })
      } else {
        findQubyid(row.teid)
          .then((res) => {
            this.editForm = res.data.data
          })
          .catch((err) => {
            this.loading = false
            this.$message.error('读取失败，请稍后再试！')
          })
      }
    },
    //将题目添加到指定的试卷
    addToPaper() {},
    // 搜索事件
    search() {
      this.getdata(this.formInline)
    },
    // 关闭编辑的弹出框
    closeDialog() {
      this.editFormVisible = false
    },
    //提交抽屉中的表单操作
    handleClose(done) {
      if (this.loading) {
        return
      }
      this.$confirm('确定要添加到该试卷吗？')
        .then(() => {
          //保存试卷中题目的ids
          let ids = []
          for (var key in JSON.parse(this.paperItem.item)) {
            this.paperItem.tids.push({
              ids: key,
              score: JSON.parse(this.paperItem.item)[key].score,
            })
            ids.push(this.paperItem.tids.shift())
          }
          //点击详情添加题目
          for (let i = 0; i < this.editForm.length; i++) {
            if (this.editForm[0].topic != '') {
              if (ids.indexOf(this.editForm[i].id) == -1) {
                this.paperItem.tids.push({
                  ids: this.editForm[i].id,
                  score: this.form.score,
                })
                //添加题目至试卷
                addItemToPaper(this.paperItem)
              } else {
                alert('该题目已存在！')
              }
            }
          }
          //批量添加题目
          if (this.editForm[0].topic == '') {
            for (
              let i = 0;
              i < this.$refs.multipleTable.selection.length;
              i++
            ) {
              if (ids.indexOf(this.$refs.multipleTable.selection[i].id) == -1) {
                this.paperItem.tids.push({
                  ids: this.$refs.multipleTable.selection[i].id,
                  score: this.form.score,
                })
                //添加题目至试卷
                addItemToPaper(this.paperItem)
              } else {
                alert(
                  '题目' + this.$refs.multipleTable.selection[i].id + '已存在！'
                )
              }
            }
          }
          //更新单选框试卷中的值
          findPaperItemByCategoryId(this.paperItems[0].cid).then((res) => {
            this.paperItems = res.data.data
            this.paperItem = ''
            this.form.score = ''
          })
          //关闭详情弹窗
          this.closeDialog()
          done()
          // 动画关闭需要一定的时间
          this.loading = false
        })
        .catch(() => {})
    },
    cancelForm() {
      this.loading = false
      this.dialog = false
      clearTimeout(this.timer)
    },
    //试卷列表级联菜单发生改变时的操作
    handlechange(value) {
      findPaperItemByCategoryId(value[value.length - 1]).then((res) => {
        this.paperItems = res.data.data
        this.paperItem = ''
      })
    },
    // 格式化数据，递归将空的children置为undefined
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].paperCategories.length < 1) {
          data[i].paperCategories = undefined
        } else {
          this.formatData(data[i].paperCategories)
        }
      }
      return data
    },
    changeEdit(newVal) {
      if (newVal == false) {
        this.editForm = [
          {
            topic: '',
            options: [],
            typeid: '',
            text: '',
          },
        ]
      }
    },
  },
  // 创建前状态(里面是操作)
  beforeCreate() {},
  // 创建完毕状态(里面是操作)
  created() {
    iList().then((res) => {
      if (res.data.code == 200) {
        this.data = res.data.data
      }
    }),
      (this.title = this.$route.name.split('/')),
      this.getdata(this.formInline),
      pList().then((res) => {
        if (res.data.code == 200) {
          this.tableData2 = this.formatData(res.data.data)
        }
      })
  },
  // 挂载前状态(里面是操作)
  beforeMount() {},
  // 挂载结束状态(里面是操作)
  mounted() {},
  mounted() {},
  // 更新前状态(里面是操作)
  beforeUpdate() {},
  // 更新完成状态(里面是操作)
  updated() {},
  // 销毁前状态(里面是操作)
  beforeDestroy() {},
  // 销毁完成状态(里面是操作)
  destroyed() {},
}
</script>

// scoped 样式只在本组件使用
<style scoped>
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.list-search {
  margin-top: 20px;
}
</style>
